package cn.zhentao.controller;

import cn.zhentao.util.JwtHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 测试控制器
 * 用于验证JWT令牌的功能
 */
@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    private JwtHelper jwtHelper;

    /**
     * 测试JWT令牌验证
     * 需要有效的JWT令牌才能访问
     */
    @GetMapping("/jwt")
    public Map<String, Object> testJwt() {
        Map<String, Object> result = new HashMap<>();
        
        String username = jwtHelper.getCurrentUsername();
        Long userId = jwtHelper.getCurrentUserId();
        boolean isValid = jwtHelper.isCurrentTokenValid();
        boolean isNearExpiration = jwtHelper.isCurrentTokenNearExpiration();
        
        result.put("code", 200);
        result.put("message", "JWT令牌验证成功");
        result.put("data", Map.of(
            "username", username,
            "userId", userId,
            "isValid", isValid,
            "isNearExpiration", isNearExpiration
        ));
        
        return result;
    }

    /**
     * 测试受保护的接口
     * 需要有效的JWT令牌才能访问
     */
    @PostMapping("/protected")
    public Map<String, Object> testProtected(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        
        String username = jwtHelper.getCurrentUsername();
        Long userId = jwtHelper.getCurrentUserId();
        
        result.put("code", 200);
        result.put("message", "受保护接口访问成功");
        result.put("data", Map.of(
            "username", username,
            "userId", userId,
            "requestData", request
        ));
        
        return result;
    }

    /**
     * 获取当前用户信息
     * 需要有效的JWT令牌才能访问
     */
    @GetMapping("/user-info")
    public Map<String, Object> getUserInfo() {
        Map<String, Object> result = new HashMap<>();
        
        String username = jwtHelper.getCurrentUsername();
        Long userId = jwtHelper.getCurrentUserId();
        String token = jwtHelper.getCurrentToken();
        
        result.put("code", 200);
        result.put("message", "获取用户信息成功");
        result.put("data", Map.of(
            "username", username,
            "userId", userId,
            "token", token != null ? token.substring(0, Math.min(20, token.length())) + "..." : null
        ));
        
        return result;
    }
} 